<template>
  <el-dialog :title="{ add: '新增部门', edit: '编辑部门'}[mode]" width="700px" :visible.sync="isShow" @close="closeEvent">
    <!-- 表单验证
    基本需求：必填，长度1-50
       1：el-form 绑定  model,rules,ref
       2:el-form-item   prop
       3:rules:{
           prop对应的值:[
           {required:true,message:"错误信息",trigger:"change"},
           {min:1,max:50,message:"请输入1-50字符",trigger:"change"}，
           {validator:(rule,value,callback)=>{
               value:当前验证项的值
               callback:正常通过,callback(),失败 callback(new Error('错误信息'))
           },trigger:"change/blur"}
           ]
       }
    全局表单验证
      1:el-form  ref
      2:this.$refs.ref值.validate((result)=>{
          result:true:验证通过,false:验证失败
      })

 -->
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <!--
             1:定义api
             2:导入
             3：调用
               在获取焦点时调用接口

           -->
        <el-select v-model.trim="form.manager" @focus="focusEvent">
          <el-option
            v-for="i in managerList"
            :key="i.id"
            :label="i.username"
            :value="i.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="cancelEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysUserSimple, companyDepartmentPost, companyDepartmentPut } from '@/api/departments.js'
export default {
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add',
      isShow: false,
      managerList: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      item: '',
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输如1-50个字符', trigger: 'change' },
          { validator: (rule, value, callback) => {
            let resultArr = []
            if (this.mode === 'add') {
              resultArr = this.initList.filter(i => {
                if (i.pid === this.item.id) {
                  return true
                }
              })
            } else if (this.mode === 'edit') {
              resultArr = this.initList.filter((i) => {
                if (i.pid === this.item.pid && i.name !== this.item.name) {
                  return true
                }
              })
            }
            // 判断输入是否重名
            const bol = resultArr.some((i) => {
              return i.name === value
            })
            bol ? callback(new Error('部门名重复')) : callback()
          } }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输如1-50个字符', trigger: 'change' },
          { validator: (rule, value, callback) => {
            let bol = true
            if (this.mode === 'add') {
              bol = this.initList.some(i => {
                return i.code === value
              })
            } else if (this.mode === 'edit') {
              bol = this.initList.some(i => {
                return i.code === value && i.id !== this.item.id
              })
            }
            bol ? callback(new Error('部门编码重复')) : callback()
          } }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输如1-50个字符', trigger: 'change' }
        ]
      }
    }
  },
  //   watch: {
  //     isShow: {
  //       handler(newVal) {
  //         if (!newVal) {
  //           this.$refs.form.resetFields()
  //         }
  //       }
  //     }
  //   },
  mounted() {
    this.$bus.$on('addEvent', (show, item, mode) => {
      this.isShow = show
      this.item = item
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(this.item))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('addEvent')
  },
  methods: {
    cancelEvent() {
      this.isShow = false
    },
    async focusEvent() {
      if (!this.managerList.length) {
        const res = await sysUserSimple()
        console.log('员工简单列表', res)
        this.managerList = res.data
      }
    },
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            this.$message.success('新增成功')
          }
          if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          this.isShow = false
          this.$emit('getData')
        }
      })
    },
    closeEvent() {
      // 重置表单数据为初始化数据（表单第一次渲染时的数据），清除表单验证
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    }
  }
}
</script>

<style></style>
